<script setup>
import BaseButton from '@/components/base/BaseButton.vue'
import BaseInput from '@/components/base/BaseInput.vue'
import EmailCodeInput from '@/components/auth/EmailCodeInput.vue'
import uniForms from '@dcloudio/uni-ui/lib/uni-forms/uni-forms.vue'
import uniFormsItem from '@dcloudio/uni-ui/lib/uni-forms-item/uni-forms-item.vue'
import { ref, watchEffect, computed, watch } from 'vue'
import { useUser } from '@/composables/useUser'
import { updateEmail } from '@/api/user'
import { useStore } from 'vuex'
import useLocale from '@/composables/useLocale'

const store = useStore()
const user = useUser()
const { t, locale } = useLocale()

watch(
    locale,
    () => {
        uni.setNavigationBarTitle({
            title: t('changeEmail'),
        })
    },
    { immediate: true },
)

watchEffect(() => {
    if (!user.value?.email) {
        uni.setNavigationBarTitle({ title: t('bindEmail') })
    }
})

const formData = ref({
    email: '',
    code: '',
    password: '',
    confirmPassword: '',
})
const formRef = ref(null)

const fields = computed(() => {
    const res = {
        email: {
            placeholder: t('pleaseEnterNewEmail'),
            component: BaseInput,
            type: 'email',
            rules: [
                {
                    required: true,
                    errorMessage: t('pleaseEnterEmail'),
                },
                {
                    format: 'email',
                    errorMessage: t('pleaseEnterCorrectEmail'),
                },
            ],
        },
        code: {
            placeholder: t('pleaseEnterCode'),
            component: EmailCodeInput,
            rules: [
                {
                    required: true,
                    errorMessage: t('pleaseEnterCode'),
                },
            ],
        },
    }
    if (!user.value.email) {
        res.password = {
            placeholder: t('pleaseEnterPassword'),
            component: BaseInput,
            password: true,
            type: 'password',
            rules: [
                {
                    required: true,
                    errorMessage: t('pleaseEnterPassword'),
                },
            ],
        }
        res.confirmPassword = {
            placeholder: t('pleaseConfirmPassword'),
            component: BaseInput,
            password: true,
            type: 'password',
            rules: [
                {
                    required: true,
                    errorMessage: t('pleaseConfirmPassword'),
                },
                {
                    validateFunction: function (rule, value, data, callback) {
                        if (data.confirmPassword !== data.password) {
                            callback(t('passwordsNotMatch'))
                        }
                        return true
                    },
                },
            ],
        }
    }
    return res
})

async function handleSubmit() {
    try {
        const data = await formRef.value.validate()
        uni.showLoading()
        const resp = await updateEmail({
            email: data.email,
            code: data.code,
            password: user.value.email ? undefined : data.password,
        })
        uni.hideLoading()
        if (resp.status === 200) {
            uni.showToast({
                title: user.value.email ? t('changeSuccess') : t('bindSuccess'),
                icon: 'none',
            })
            store.dispatch('user/setUser')
            uni.navigateBack()
        }
    } catch (_) {
        /* empty */
    }
}
</script>

<template>
    <view class="flex justify-center px-8">
        <view class="flex w-full max-w-96 flex-col gap-3 pt-20">
            <uni-forms ref="formRef" :model-value="formData">
                <uni-forms-item
                    v-for="({ rules, ...attrs }, name) in fields"
                    :key="name"
                    :rules="rules"
                    :name="name"
                >
                    <EmailCodeInput
                        v-if="name === 'code'"
                        v-bind="attrs"
                        v-model="formData[name]"
                        :email="name === 'code' ? formData.email : undefined"
                    />
                    <BaseInput v-else v-bind="attrs" v-model="formData[name]" />
                </uni-forms-item>
            </uni-forms>
            <BaseButton @click="handleSubmit">
                {{ user.email ? t('confirmChange') : t('bind') }}
            </BaseButton>
        </view>
    </view>
</template>
